package com.macaline.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.macaline.entity.Role;
import com.macaline.entity.User;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


/**
 *
 * @author warm_joy
 *<p>Description:  redis的配置类</p>
 *<p>date: 2019-06-20 17:49</p>
 *<p>company: www.leimingyun.com </p>
 */
@Configuration
public class RedisConifg {

    @Bean
    @Primary
    CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        // 配置序列化（解决乱码的问题）
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(60))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerialize()))
                .disableCachingNullValues();

        return RedisCacheManager.builder(connectionFactory).cacheDefaults(config).build();
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        template.setValueSerializer(jackson2JsonRedisSerialize());
        template.afterPropertiesSet();
        return template;
    }

    private Jackson2JsonRedisSerializer jackson2JsonRedisSerialize(){
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        return jackson2JsonRedisSerializer;
    }

	/**
	 *
	* <p>@author warm_joy </p>
	* <p>Description: 设置储存实体类的Template和序列化配置</p>
	* <p>Date: 2019-06-20 17:42</p>
	* @param redisConnectionFactory
	* @return
	 */
	@Bean
    public RedisTemplate<Object, User> userRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		// 1.创建 redisTemplate 模版
        RedisTemplate<Object, User> template = new RedisTemplate<Object, User>();
        // 2.关联 redisConnectionFactory
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<User> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<User>(User.class);
        // 3.创建 序列化类
        template.setDefaultSerializer(jackson2JsonRedisSerializer);
        return template;
    }

	@Bean
    public RedisTemplate<Object, Role> roleRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		// 1.创建 redisTemplate 模版
        RedisTemplate<Object, Role> template = new RedisTemplate<Object, Role>();
        // 2.关联 redisConnectionFactory
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Role> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Role>(Role.class);
        // 3.创建 序列化类
		template.setDefaultSerializer(jackson2JsonRedisSerializer);
        return template;
    }


	@Bean
    public RedisTemplate<String, Object> objectRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		// 1.创建 redisTemplate 模版
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 2.关联 redisConnectionFactory
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        // 3.创建 序列化类
		template.setDefaultSerializer(jackson2JsonRedisSerializer);
        return template;
    }




	/**
	 *
	* <p>@author warm_joy </p>
	* <p>Description:json格式序列化器 </p>
	* <p>Date: 2019-06-22 11:19</p>
	* @return
	 */
	@Bean
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public RedisSerializer<Object> jackson2JsonRedisSerializer() {
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
		Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);
        return serializer;
    }

	 /**
	  *
	 * <p>@author warm_joy </p>
	 * <p>Description: 配置redis管理配置</p>
	 * <p>Date: 2019-06-22 14:26</p>
	 * @param lettuceConnectionFactory
	 * @return
	  */
    @Bean
    public CacheManager userCacheManager(RedisConnectionFactory lettuceConnectionFactory) {
    	 // 生成一个默认配置，通过config对象即可对缓存进行自定义配置
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();
        // 设置缓存管理器管理的缓存的默认过期时间
        defaultCacheConfig = defaultCacheConfig
//        		.entryTtl(Duration.ofSeconds(100))
                // 设置 key为string序列化
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                /**
                 *  设置value为json序列化,应该将所有的保存到redis的数据类都加入这里
                 */
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new Jackson2JsonRedisSerializer<User>(User.class)))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new Jackson2JsonRedisSerializer<Role>(Role.class)))
                // 不缓存空值
                .disableCachingNullValues();
        // 设置一个初始化的缓存空间set集合
        Set<String> cacheNames= new HashSet<>();
        cacheNames.add("user");

        // 对每个缓存空间应用不同的配置
        Map<String,RedisCacheConfiguration> configMap = new HashMap<>();
        configMap.put("user",defaultCacheConfig.entryTtl(Duration.ofSeconds(100)));

        // 使用自定义的缓存配置初始化一个cacheManager
        RedisCacheManager cacheManager = RedisCacheManager.builder(lettuceConnectionFactory)
                .cacheDefaults(defaultCacheConfig)
                // 注意这两句的调用顺序，一定要先调用该方法设置初始化的缓存名，再初始化相关的配置
                .initialCacheNames(cacheNames)
                .withInitialCacheConfigurations(configMap)
                .build();
        return  cacheManager;
    }

}
